package com.nbsaas.boot.app.ext.resource;

import com.nbsaas.boot.app.api.apis.AppMenuApi;
import com.nbsaas.boot.app.api.domain.field.AppMenuField;
import com.nbsaas.boot.app.api.domain.simple.AppMenuSimple;
import com.nbsaas.boot.app.ext.apis.AppMenuTenantExtApi;
import com.nbsaas.boot.app.ext.domain.simple.AppMenuExtSimple;
import com.nbsaas.boot.app.ext.helper.TreeHelper;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ListResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AppMenuTenantExtResource implements AppMenuTenantExtApi {

    @Resource
    private AppMenuApi appMenuApi;

    @Transactional(readOnly = true)
    @Override
    public ListResponse<AppMenuExtSimple> root(Long tenantId, Long appId) {
        return root(tenantId, appId, false);
    }

    @Transactional(readOnly = true)
    @Override
    public ListResponse<AppMenuExtSimple> root(Long tenantId, Long appId, Boolean handleDisabled) {
        ListResponse<AppMenuExtSimple> result = new ListResponse<>();

        //获取系统菜单
        List<AppMenuSimple> menus = appMenuApi.listData(
                Filter.eq(AppMenuField.app, appId),
                Filter.eq(AppMenuField.menuType, 1)
        );


        List<AppMenuSimple> tenantMenus = appMenuApi.listData(
                Filter.eq(AppMenuField.tenantId, tenantId),
                Filter.eq(AppMenuField.menuType, 2)
        );

        if (tenantMenus != null) {
            menus.addAll(tenantMenus);
        }

        result.setData(TreeHelper.makeTree(menus, handleDisabled));
        return result;
    }

    @Override
    public ListResponse<AppMenuExtSimple> findByRole(Long tenantId, Long appId, Long role) {
        return null;
    }
}
